package com.yj.service;

import com.alibaba.dashscope.app.Application;
import com.alibaba.dashscope.app.ApplicationParam;
import com.alibaba.dashscope.app.ApplicationResult;
import com.yj.entity.ChatContent;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class QytwChatService implements ChatService, ApplicationContextAware {


    private Application application;

    private ApplicationParam applicationParam;

    private ApplicationContext applicationContext;

    public QytwChatService(Application application){
        this.application = application;
    }

    @SneakyThrows
    @Override
    public ChatContent chat(String message) {
        log.info("QytwChatService chat message: {}", message);

        ChatContent chatContent = new ChatContent();
        chatContent.setMessage(message);
        chatContent.setSendTime(new Date());
        chat(chatContent);
        return chatContent;
    }

    @SneakyThrows
    @Override
    public ChatContent chat(ChatContent content) {
        log.info("QytwChatService chat message: {}", content);
        content.setSendTime(new Date());

        // 获取一个新的 applicationParam 实例
        ApplicationParam applicationParam = applicationContext.getBean(ApplicationParam.class);
        applicationParam.setPrompt(content.getMessage());
        applicationParam.setSessionId(content.getSessionId());


        ApplicationResult applicationResult = application.call(applicationParam);

        log.info("requestId: {}, text: {}, finishReason: {}\n",
                applicationResult.getRequestId(), applicationResult.getOutput().getText(), applicationResult.getOutput().getFinishReason());

        // 对话内容
        String resText = applicationResult.getOutput().getText();

        // 请求ID
        String requestId = applicationResult.getRequestId();

        // 保存对话记录
        String sessionId = applicationResult.getOutput().getSessionId();

        content.setReceivedMessage(resText);
        content.setRequestId(requestId);
        content.setSessionId(sessionId);
        content.setMessageType("QYTW");

        // TODO 保存对话记录到数据库

        return content;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
